package com.uiotsoft.small.app.sampler.mqtt;

import com.uiotsoft.small.app.entity.AppClient;
import com.uiotsoft.small.app.service.deviceControl.DeviceControl;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeviceControlBlockSampler extends AbstractJavaSamplerClient {
    private AppClient appClient;
    private int deviceId;
    private String properties;
    private static final Logger log = LoggerFactory.getLogger(DeviceControlBlockSampler.class);
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("deviceId", "204");
        params.addArgument("properties", "{\"powerSwitch\":\"on\"}");
        return params;
    }

    private void setupValues(JavaSamplerContext context) {
        deviceId = Integer.parseInt(context.getParameter("deviceId"));
        properties = context.getParameter("properties");

    }
    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        setupValues(javaSamplerContext);
        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        SampleResult results = new SampleResult();
        appClient = (AppClient) vars.getObject("appClient");
        results.setDataEncoding("UTF-8");
        results.sampleStart();
        if (appClient != null){
            DeviceControl deviceControl = new DeviceControl(appClient);
            if (deviceControl.controlBlock(deviceId,properties)){
                log.info("发送控制协议成功……");
                results.sampleEnd();
                results.setSuccessful(true);
                results.setResponseData("OK", "UTF-8");
                return results;
            }else {
                results.setSuccessful(false);
                results.setResponseData("发送控制协议失败！", "UTF-8");
            }
        }else {
            results.setSuccessful(false);
            results.setResponseData("AppClient is null！", "UTF-8");

        }
        results.sampleEnd();
        return results;
    }
}
